package com.thread.sync.sync10;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyCustom02 implements Runnable {
    //并发数字运算
    private static AtomicInteger count = new AtomicInteger(0);

    @Override
    public void run() {
        try {
            int temp = count.incrementAndGet();//count累加,区分任务
            System.out.println("任务" + temp);
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        //无界队列
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
        ExecutorService executor = new ThreadPoolExecutor(
                5,
                10,//无界时,任务多会一直添加到队列中,不会创建新的线程,线程数会一直是核心数量
                120L,
                TimeUnit.SECONDS,
                queue //指定无界队列
        );
        for (int i = 0; i < 20; i++) {
            executor.execute(new MyCustom02()); //会5个一起执行
        }
        Thread.sleep(1000);
        System.out.println("queue size:" + queue.size());
        Thread.sleep(2000);
    }
}
